package xmldao;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import contatoplugin.ContatoAbstract;
import daobase.IDao;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;
import usuarioplugin.UsuarioAbstract;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Bush
 */
public class SerializacaoXml implements IDao {

    private File arquivo = new File("src/pessoas/data/contatos.xml");
    private File arquivoInvalido = new File("src/pessoas/data/contatosInvalidos.xml");
    private File arquivoUsuarios = new File("src/pessoas/data/usuarios.xml");

    @Override
    public void gravarContato(ContatoAbstract c) {
        try {
            String xml = "<pessoas.model.Contato>\n"
                    + "    <nome>" + c.getNome() + "</nome>\n"
                    + "    <sobrenome>" + c.getSobrenome() + "</sobrenome>\n"
                    + "    <telefone>" + c.getTelefone() + "</telefone>\n"
                    + "    <id>" + c.getId() + "</id>\n"
                    + "    <uf>" + c.getUf() + "</uf>\n"
                    + "    <operadora>" + c.getOperadora() + "</operadora>\n"
                    + " </pessoas.model.Contato>";

            String antigo = tiraUltimaTag(arquivo);
            FileWriter w = new FileWriter(arquivo, false);
            PrintWriter pw = new PrintWriter(w);
            pw.print(antigo);
            pw.println(xml);
            pw.println("</list>");
            pw.close();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }

    @Override
    public void liparGravarContatos(ArrayList c) {
        try {
            String xml = "";
            if (!c.isEmpty()) {
                XStream parser = new XStream(new DomDriver());
                parser.setMode(XStream.NO_REFERENCES);
                xml = parser.toXML(c);
            }
            FileWriter w;
            w = new FileWriter(arquivo, false);
            BufferedWriter bf = new BufferedWriter(w);
            long inicio = System.currentTimeMillis();
            bf.write(xml);
            long fim = System.currentTimeMillis();
            if (fim - inicio > 5000) {
                throw new Exception("Excedeu tempo limite de Exportação");
            }
            bf.close();
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }

    @Override
    public ArrayList lerContatos() {
        Scanner scan;
        String linha = "";
        try {
            scan = new Scanner(arquivo);
            while (scan.hasNextLine()) {
                linha += scan.nextLine();
            }
        } catch (FileNotFoundException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
        if (linha.trim().isEmpty()) {
            return new ArrayList();
        }
        return lerContatoXML(linha);
    }

    @Override
    public void gravarContatosInvalido(ContatoAbstract c) {
        try {
            String xml = "<pessoas.model.Contato>\n"
                    + "    <nome>" + c.getNome() + "</nome>\n"
                    + "    <sobrenome>" + c.getSobrenome() + "</sobrenome>\n"
                    + "    <telefone>" + c.getTelefone() + "</telefone>\n"
                    + "    <id>" + c.getId() + "</id>\n"
                    + "    <uf>" + c.getUf() + "</uf>\n"
                    + "    <operadora>" + c.getOperadora() + "</operadora>\n"
                    + " </pessoas.model.Contato>";

            String antigo = tiraUltimaTag(arquivoInvalido);
            FileWriter w = new FileWriter(arquivoInvalido, false);
            PrintWriter pw = new PrintWriter(w);
            pw.print(antigo);
            pw.println(xml);
            pw.println("</list>");
            pw.close();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }

    @Override
    public void limpaGravaContatoInvalido(ArrayList c) {
        try {
            String xml = "";
            if (!c.isEmpty()) {
                XStream parser = new XStream(new DomDriver());
                parser.setMode(XStream.NO_REFERENCES);
                xml = parser.toXML(c);
            }
            FileWriter w;
            w = new FileWriter(arquivoInvalido, false);
            BufferedWriter bf = new BufferedWriter(w);
            bf.write(xml);
            bf.close();
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }

    @Override
    public ArrayList lerContatosInvalido() {
        Scanner scan;
        String linha = "";
        try {
            scan = new Scanner(arquivoInvalido);
            while (scan.hasNextLine()) {
                linha += scan.nextLine();
            }
        } catch (FileNotFoundException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
        if (linha.trim().isEmpty()) {
            return new ArrayList();
        }
        return lerContatoXML(linha);
    }

    @Override
    public ArrayList carregaUsuarios() {
        Scanner scan;
        String linha = "";
        try {
            scan = new Scanner(arquivoUsuarios);
            while (scan.hasNextLine()) {
                linha += scan.nextLine();
            }
        } catch (FileNotFoundException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
        if (linha.trim().isEmpty()) {
            return new ArrayList();
        }
        return lerUsuarioXML(linha);
    }

    @Override
    public void gravaUsuario(UsuarioAbstract u) {
        try {
            String xml = "	<pessoas.model.Usuario>\n"
                    + "		<nomeUsuario>" + u.getNomeUsuario() + "</nomeUsuario>\n"
                    + "		<senhaUsuario>" + u.getSenhaUsuario() + "</senhaUsuario>\n"
                    + "	</pessoas.model.Usuario>";

            String antigo = tiraUltimaTag(arquivoUsuarios);
            FileWriter w = new FileWriter(arquivoUsuarios, false);
            PrintWriter pw = new PrintWriter(w);
            pw.print(antigo);
            pw.println(xml);
            pw.println("</list>");
            pw.close();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }

    @Override
    public void limpaGravaUsuario(ArrayList u) {
        try {
            String xml = "";
            if (!u.isEmpty()) {
                XStream parser = new XStream(new DomDriver());
                parser.setMode(XStream.NO_REFERENCES);
                xml = parser.toXML(u);
            }
            FileWriter w;
            w = new FileWriter(arquivoUsuarios, false);
            BufferedWriter bf = new BufferedWriter(w);
            bf.write(xml);
            bf.close();
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }

    public ArrayList lerContatoXML(String xml) {
        XStream parser = new XStream(new DomDriver());
        parser.setMode(XStream.NO_REFERENCES);
        ArrayList<Contato> listaXML = (ArrayList<Contato>) parser.fromXML(xml);
        return listaXML;
    }

    public ArrayList lerUsuarioXML(String xml) {
        XStream parser = new XStream(new DomDriver());
        parser.setMode(XStream.NO_REFERENCES);
        ArrayList<Usuario> listaXML = (ArrayList<Usuario>) parser.fromXML(xml);
        return listaXML;
    }

    private String tiraUltimaTag(File caminho) throws FileNotFoundException, Exception {
        Scanner scan = new Scanner(caminho);
        String linha = "";
        while (scan.hasNextLine()) {
            linha += scan.nextLine() + "\n";
        }
        if (linha.trim().isEmpty()) {
            linha += "<list>\n";
        }
        linha = linha.replace("</list>", "    ");
        return linha;
    }

}
